//
//  NewfeatureViewController.swift
//  SinaBlog
//
//  Created by ChenWei on 15/10/31.
//  Copyright © 2015年 cw. All rights reserved.
//

import UIKit
import SnapKit

private let CWNewfeatureReuseIdentifierCell = "CWNewfeatureReuseIdentifierCell"

class NewfeatureViewController: UICollectionViewController {
    /// 新特性界面count
    private let imageCount = 4
    /// 布局参数
    private var layout = NewfeatureLayout()

    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        //self.clearsSelectionOnViewWillAppear = false

        //1. 注册cell
        self.collectionView!.registerClass(NewfeatureCell.self, forCellWithReuseIdentifier: CWNewfeatureReuseIdentifierCell)
    }
    
    // MARK: - UICollectionViewDataSource
    /// 新界面的页数
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageCount
    }
    
    /// 显示cell时调用
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CWNewfeatureReuseIdentifierCell, forIndexPath: indexPath) as! NewfeatureCell
        cell.imageIndex = indexPath.row + 1
        
        return cell
    }
    /// 完全显示cell后调用
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 判断是否是最后一页
        let path = collectionView.indexPathsForVisibleItems().last!
        if path.item == imageCount - 1 { // 最后一页
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewfeatureCell
            cell.startButton.hidden = false
            cell.startAnimation()
        }
    }
}

// MARK: - NewfeatureCell
class NewfeatureCell: UICollectionViewCell {
    var imageIndex : Int = 0 {
        didSet {
            // 设置背景图片
            let image = UIImage(named: "new_feature_\(self.imageIndex)")
            imageViewIcon.image = image
            // 隐藏开始按钮
            startButton.hidden = true
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        // 1.初始化UI
       setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 添加并布局UI
    private func setupUI() {
        // 1.添加子控件
        contentView.addSubview(imageViewIcon)
        contentView.addSubview(startButton)
        
        // 2.布局子控件
        imageViewIcon.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(0)
        }
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-160)
        }
    }
    
    // MARK: - NewfeatureCell内部控制方法
    /// "开始按钮"动画
    private func startAnimation() {
//        startButton.hidden = false
        startButton.userInteractionEnabled = false
        startButton.transform = CGAffineTransformMakeScale(0.0, 0.0)
       
        // http://www.renfei.org/blog/ios-8-spring-animation.html
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                self.startButton.userInteractionEnabled = true
        }
    }
    
    /// 监听开始按钮点击
    @objc private func startButtonClick() {
        NSLog("startButtonClick")
        // 发送通知更改根控制器,进入"首页"控制器
        NSNotificationCenter.defaultCenter().postNotificationName(CWSwitchRootViewControllerNotify, object: nil)
    }
    
    // MARK: - NewfeatureCell懒加载属性
    /// 新特性界面的背景图片
    private lazy var imageViewIcon : UIImageView = UIImageView()
    /// "开始按钮"
    private lazy var startButton : UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        btn.addTarget(self, action: Selector("startButtonClick"), forControlEvents: UIControlEvents.TouchUpInside)

        return btn
        }()

}

// MARK: - NewfeatureLayout
class NewfeatureLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        // 1.设置布局
        itemSize = UIScreen.mainScreen().bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal

        // 2.设置collectionView
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

// UICollectionView calls this when prior the layout transition animation on the incoming and outgoing layout
// 在UICollectionView的形变动画(cell显示前,ceii移除前)调用
//@available(iOS 7.0, *)
//public func prepareForTransitionToLayout(newLayout: UICollectionViewLayout)
//@available(iOS 7.0, *)
//public func prepareForTransitionFromLayout(oldLayout: UICollectionViewLayout)
//@available(iOS 7.0, *)
//public func finalizeLayoutTransition() // called inside an animation block after the transition
//
